package org.csu.mypetstore.api.controller.front;

import ch.qos.logback.core.subst.Token;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.fasterxml.jackson.core.JsonProcessingException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.csu.mypetstore.api.common.CommonResponce;
import org.csu.mypetstore.api.common.JwtInterceptor;
import org.csu.mypetstore.api.common.JwtTokenUtil;
import org.csu.mypetstore.api.entity.Account;
import org.csu.mypetstore.api.entity.Signon;
import org.csu.mypetstore.api.service.AccountService;
import org.csu.mypetstore.api.vo.AccountVO;
import org.csu.mypetstore.api.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@CrossOrigin(origins = "http://localhost:8888")
@RestController
@RequestMapping("/account/")
public class AccountController {
    @Autowired
    private AccountService accountService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private JwtInterceptor jwtInterceptor;

//    登录
    @PostMapping("tokens")
    public CommonResponce<Token> login(@RequestBody LoginVo request){
        String username=request.getUsername();
        String password=request.getPassword();
        return accountService.login(username,password);
    }

    //注册
    @PostMapping("accounts")
    public CommonResponce<AccountVO> register(@RequestBody AccountVO accountVO){
        String username=accountVO.getUsername();
        String password=accountVO.getPassword();
        return accountService.register(accountVO);
    }

    //获取用户信息
    @GetMapping("{username}")
    public CommonResponce<AccountVO> getUserInfo(@PathVariable String username){
        // 生成新的令牌
        return accountService.getAccountInformation(username);
    }

    //更新用户信息
    @PutMapping("{username}")
    public CommonResponce<String> updateUser(@PathVariable String username,
                                             @RequestBody AccountVO account,
                                             @RequestHeader("Authorization") String token){// 从请求中获取拦截器设置的属性
        try {
            // 验证 Token 所有者
            String Newusername = jwtTokenUtil.getUsernameFromToken(token.replace("Bearer ", ""));
            if (!Newusername.equals(username)) {
                return CommonResponce.createForError(1, "无权修改其他用户信息");
            }
            // 更新用户逻辑 username是原来的名字
            return accountService.updateAccount(account,username);
        }catch (Exception e){
            return CommonResponce.createForError(1,"服务器异常");
        }
    }


    // 后端 Controller 示例
    @DeleteMapping("tokens/{username}")
    public CommonResponce signout(
            @PathVariable String username,
            @RequestHeader("Authorization") String token) throws JsonProcessingException {
        // 校验 Token 中的用户是否与 username 一致
        try{
            String newtoken = token.replace("Bearer ", "").trim(); // 关键：移除前缀和空格
            String currentUser = jwtTokenUtil.getUsernameFromToken(newtoken);
            if (!currentUser.equals(username)) {
                return CommonResponce.createForError("无权操作其他用户");
            }
            return CommonResponce.createForSuccessMessage(0,"退出成功");
        }catch (Exception e) {
            System.out.println("JWT: '" + token + "'"); // 输出带引号，便于观察前后空格
            e.printStackTrace();
        }
        // 执行退出逻辑
        return CommonResponce.createForSuccessMessage(1,"退出失败");
    }

    @GetMapping("current")
    public CommonResponce<AccountVO> getCurrentUserInfo(@RequestHeader("Authorization") String token) {
        try {
            String username = jwtTokenUtil.getUsernameFromToken(token.replace("Bearer ", ""));
                return accountService.getAccountInformation(username);
        } catch (Exception e) {
            return CommonResponce.createForError(1, "Token 无效或已过期");
        }
    }
}
